<template>
	<view class="uni-pages">
		<!-- 海报 -->
		<canvas class="f__canvas" style="width:600px;height:730px"  canvas-id="firstCanvas" id="firstCanvas"></canvas>
		<!-- 生成二维码 -->
		<canvas class="f__canvas" style="width:300px;height:300px;" canvas-id="qrcode" id="qrcode"></canvas>
			
		
	</view>
</template>

<script>
	import { base64src } from "@/config/base64.js";   // 后面引用路径为base64src.js文件路径
	import _canvas from '@/uni_modules/fan-canvas/canvasUtils';// 加载万能绘制方法
	import { saveImg,qrcodeCanvas } from '@/uni_modules/fan-canvas/plugins/utils';// 需要保存图片和生成二维码可以引用此文件
	export default {
		props: {
			showShore: {
				type: Boolean,
				default: false,
			},
			detail:{
				type:Object,
				default(){
					//title ，time 时间，info圈子介绍 ，banner图片 ，dynamic_code_url个人二维码
					let data={
							  "id": '',
							  create_time:'55', //时间
							  avatar:'',   //用户头像
							  nickname:'', //昵称
							  "title": "摄影进阶课",
							  "contacts": "课程服务人",
							  //
							  label:'',
							  "contacts_code": "https://llkj-wechat.oss-cn-hangzhou.aliyuncs.com/images/20230224/fb1f7bf4668537a5f4de53f28e277597.jpg",
							  //内容
							  "content": "跟随六零去华南地区旅行，带您品尝粤式肠粉，水晶虾饺，桂林米粉，老友粉，啤酒鱼，田螺酿，加积鸭各跟随六零去华南地区旅行，带您品尝粤式肠粉，水晶虾饺，桂林米粉，老友粉，啤酒鱼，田螺酿，加积鸭各",
							  //图片
							  "filesList": [ 
								"https://llkj-wechat.oss-cn-hangzhou.aliyuncs.com/images/20230224/0f184e69a58ef530179a10449da4a454.png"
							  ],
							  //个人二维码
							  "dynamic_code_url": "",
							}
					return data;
				},
			},
			labelName:{
				type:String,
				default(){
					return "基地管家"; //
				},
			},
			labelColor:{
				type:String,
				default(){
					return "#F24F40";
				},
			},
			decArr:{ //描述
				type:Array,
				default(){
					return ["长按保存到相册","好东西记得分享"];
				},
			},
		},
		data() {
			return {
				showCanvas:false, //生成后图片弹框
				canvasImg:'',     //生成的图片
				//qrcodeImg:'',     //生成的二维码图片
			}
		},
		created() {
				
		},
		watch: {
			detail: {
				immediate: true,
				handler(newVal) {
					let flag =  this.noEmpty(newVal)
					if(flag){ //有数据
						
						//下载二维码
						let erweima = ''
						if(newVal.contacts_code){ //联系人的二维码
							erweima = newVal.contacts_code
						}
						if(newVal.class_info && newVal.class_info.teacher_info && newVal.class_info.teacher_info.wework_qr_code){
							erweima = newVal.class_info.teacher_info.wework_qr_code
						}

					}
				}
			}
		},
		computed:{
			//dangq
			bannerOne(){
				let detail = this.detail?this.detail:{};
				let img = ""
				//判断是否是数组
				if(this.isArray(detail.files)){
					if(detail.files[0].file_class == 1){
						img = detail.files[0].url
					}
				}else{
					img = detail.files
				}
				return img
			},
			
			//二维码
			erweima(){
				let erweima = ''
				let flag =  this.noEmpty(this.detail)
				if(flag){ //有数据
					let newVal = this.detail;
					erweima = newVal.dynamic_code_url
				}
				return erweima;
			},
			
			//用户信息
			userInfo(){
				// let info = {
				// 	nickname:'jok',
				// 	avatar:'https://llkj-wechat.oss-cn-hangzhou.aliyuncs.com/images/20230109/14ad7833949d953e800fa82e74061bc4.jpg',
				// 	label_name:' 基地管家',
				// 	label_color:'#F24F40',
				// }
				
			   let info =	this.customeInfoGet()
			 //    if(!info){
				// 	info = {}
				// }
				// info.label_name = '基地管家'
				// info.label_color = '#F24F40'
			   return info;
			},
			
			
		},
		mounted() {
			// this.createQrcode()
		},
		onReady() {
			
			//二维码
			
		},
		methods:{
			//绘制海报
			async createGoodsPoster() {
				var that = this;

				  let detail = this.detail
				  if(!this.noEmpty(detail)){
					  //uni.$u.toast("话题不能为空");
					  return;
				  }
				
					
				 //已经生成直接显示	
			  //    if(this.canvasImg){
					// //this.showCanvas = true;
					// that.sendYou();
			  //    	return
			  //    }
			 	
			 	uni.showLoading({
			 		title: '海报生成中'
			 	});
			     const cvsW = 600;
			 	 const cvsH = 730;
			     const goodsH = 300;
				 const logo_daxue_w = 86
				 const logo_daxue_h = 104
			 	 const logo_w = 100;
			     const marginLeft = 50;
				
			 	let family = " 'PingFang SC',tahoma,arial,'helvetica neue','hiragino sans gb','microsoft yahei',sans-serif";
			 	let ctx = uni.createCanvasContext('firstCanvas',this);
			     // 绘制矩形 背景色
			 	_canvas.fillRoundRect(ctx,0,0,cvsW,cvsH,20,"#F24F40");
			    // 绘制矩形 背景白色
				_canvas.fillRoundRect(ctx,30,25,cvsW-60,cvsH-50,10,"#fff");
				try{
					 let logoTop = 40; //
					// 绘制圆形头像
					let userAvatar =  that.detail.avatar  //获取用户头像 
					if(userAvatar){
						userAvatar = userAvatar.replace('http://', 'https://')
						userAvatar = userAvatar.replace('https://thirdwx.qlogo.cn', 'https://wx.qlogo.cn')
						let avatarInfo =  await this.getImageInfoApi(userAvatar);
						console.log("用户头像-----------",{avatarInfo})
						_canvas.drawCircular(ctx, avatarInfo.path, marginLeft, logoTop, logo_w, logo_w);
					}
					
				    // 用户名称
				   let nickname = that.detail.nickname
				   ctx.setFillStyle('#000000')
				   ctx.font = "bold 26px" + family
				   let metrics = ctx.measureText(nickname) 
				   let metricsWidth = metrics.width  //字体的宽度
				   ctx.fillText(nickname, logo_w+marginLeft+20, logoTop + 30)
				
					//时间 1天前
					let time = that.detail.create_time
					ctx.setFillStyle('#999')
					ctx.font = "23px" + family
					ctx.fillText(time, logo_w+marginLeft+20, logoTop + 80)
					
					// 绘制圆角按钮
					// 参数：cxt、背景颜色、x坐标、y坐标、宽度、高度、圆角、文字、文字颜色、文字位置
					if(that.detail.label){
						let label_color = that.labelColor
						let label_name = that.detail.label
						ctx.font = '20px' + family
						_canvas.drawButton(ctx,label_color , marginLeft + logo_w + metricsWidth + 60, logoTop+5, 120, 42, 21, label_name, '#ffffff', 'center')
					}
				
					//高度
					logoTop = logoTop+logo_w + 0
					// 简介-多行文字
					ctx.setFillStyle('#333')
					ctx.textAlign = 'left';
					var options = {
						font:"bold 28px"+family,     //设置字体
						ctx:ctx,
						word: that.detail.content,      //文本
						maxWidth:cvsW-120,                //最大宽度
						maxLine:2,                   //最大行数--超出省略
						x:marginLeft,   //x坐标
						y:logoTop,                  //y坐标
						l_h:40                  //行高
					}
					_canvas.dealWords(options)  // 文本自定义换行
					//高度
					logoTop = logoTop+ 110
					// 同步加载图片
					if(that.bannerOne){
						let shopimg = await this.getImageInfoApi(that.bannerOne);
						console.log("海报商品图片",{shopimg})
						 _canvas.drawImgCover(ctx, shopimg, marginLeft, logoTop, cvsW-100, goodsH);   // 绘制商品图片
						 ctx.save();  // save+clip+restore:防止图片超出边框显示--相当于overflow: hidden;
						 ctx.clip(); //剪切--不允许超出矩形框
						 ctx.restore();
					}
		   		   

					//高度
					 logoTop = logoTop+20 +goodsH
			        // 绘制二维码
					 if(that.erweima){
						base64src(that.erweima, (url) => {
							console.log('海报个人二维码',url)
							ctx.drawImage(url, marginLeft, logoTop, 120, 120);
						})
					 }
			     
					 //长按图片扫描二维码加入学习
					  ctx.setFillStyle('#000000')
					 ctx.font = '25px bold' + family
					 ctx.fillText(that.decArr[0], 120+marginLeft+20, logoTop+30)
					 ctx.font = '25px ' + family
					 ctx.fillText(that.decArr[1], 120+marginLeft+20, logoTop+30+42)
			         //绘制图片
			 		ctx.draw(false, function() {
			 			uni.canvasToTempFilePath({
			 				width: cvsW,
			 				height: cvsH,
			 				canvasId: 'firstCanvas',
			 				success(res) {
			 					uni.hideLoading();
			 					that.canvasImg = res.tempFilePath
								//that.showCanvas = true;  //弹框
								that.sendYou();
								console.log("---------res.tempFilePath",res.tempFilePath)
			 				}
			 			},that)
			 		}, 500)
				}catch(e){
					console.log("海报制作失败",e)
					uni.hideLoading();
					// uni.showToast({
					// 	title: '海报制作失败',
					// 	icon: 'none'
					// });
					that.canvasImg = ''
					that.sendYou();
					return;
				}
			 },
			// 创建二维码
			createQrcode(){
			    var that = this
				//安卓不能生成二维码  自定义组件不能生成
			    qrcodeCanvas('qrcode', 'https://www.baidu.com', 600, 600);
			    const ctx = uni.createCanvasContext('qrcode',this);
				console.log('--111111111------------------',ctx)
			    ctx.draw(true, function() {
			        uni.canvasToTempFilePath({
			            width: 600,
			            height: 600,
			            canvasId: 'qrcode',
			            success(res) {
							console.log('--------------------',res)
							//alert(JSON.stringify(res))
			                // 二维码本地图
			                that.qrcodeImg = res.tempFilePath
			                console.log('createQrcodecreateQrcode',res,'createQrcode')
			            }
			        },that)
			    })
			},
			// 保存图片
			async onSaveImg() {
				let imgUrl = "";
				if(this.canvasImg){
					//console.log(this.canvasImg)
					imgUrl = await this.canvasImg;
			        saveImg(imgUrl,()=>{
						this.showCanvas  = false 
					})
				}
			},
			//关闭
			chioceCloseShare(){
				this.$emit('close')
			},
			//获取图片信息
			getImageInfoApi(url) {
				return new Promise((resolve,reject) => {
					uni.getImageInfo({
						src: url,
						success: res => {
							resolve(res);
							//resolve(res.path);
						},
						fail: err => {
							reject(err);
							console.log(err);
							// uni.showToast({
							// 	title: '网络错误请重试',
							// 	icon: 'loading'
							// });
						}
					});
				});
			},
			//获取图片信息
			downloadFileApi(url) {
				return new Promise((resolve,reject) => {
					uni.downloadFile({
						//生成临时地址
						url: url,
						success: res => {
							//resolve(res.tempFilePath);
							res.path = res.tempFilePath
							resolve(res);
						},
						fail: err => {
							reject(err);
							console.log(err);
							// uni.showToast({
							// 	title: '网络错误请重试',
							// 	icon: 'loading'
							// });
						}
					});
				});
			},
			
			//发送好友
			sendYou(){
				let imgPath = this.canvasImg
				
				this.$emit('close',imgPath)
			},
		}
	}
</script>

<style lang="scss" scoped>
	
	/* 按钮去掉边框 */
	button::after {
	  border: none;
	}
	
	.f__canvas {
		width: 300rpx;
		height: 300rpx;
		position: fixed;
		top: -10000rpx;
		left: 0rpx;
	}
	
	.canvasBox{
	    .canvasItem {
			// background-color: red;
	        /* #ifndef APP-NVUE */
	        display: flex;
	        /* #endif */
	        justify-content: center;
	        .img {
	            width: 100%;
	        }
	    }
	    .button {
	        width: 300rpx;
	        height: 80rpx;
	        background: #FF4E16;
	        line-height: 80rpx;
	        text-align: center;
	        font-size: 28rpx;
	        border-radius: 40rpx;
	        margin: 0 auto;
	        margin-top: 20rpx;
			color: #fff;
	    }
	}
</style>
